import React from 'react';
import styles from './News.css';
import {NEWS_PAGE_SIZE} from '../../constants'

import { Table, Pagination, Card, Row, Col, Modal, InputNumber, Slider, Button, Radio, Input } from 'antd';

class News extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      appName: props.params.appName,
      data: [],
      pagination: {},
      visible: false,
      searchModalVisible: false,
      starModalVisible: false,
      beginTime: new Date(),
      endTime: new Date(),
      newsScope: 'all',
      newsCustomMediaId: null,
      starMediaId: null,
      newsStarList: window.localStorage.getItem(props.params.appName + '_news_media_id_star_list') ? window.localStorage.getItem(props.params.appName + '_news_media_id_star_list').split(',') : [],
    };
  }

  componentDidUpdate() {
    if (this.props.params.appName != this.state.appName) {
      this.setState({
        appName: this.props.params.appName,
        newsStarList: window.localStorage.getItem(this.props.params.appName + '_news_media_id_star_list') ? window.localStorage.getItem(this.props.params.appName + '_news_media_id_star_list').split(',') : [],
      })
    }
  }

  handleTableChange(pagination, filters, sorter) {
    this.props.dispatch({type: 'weixin/fetchNews', payload: {page: pagination.current - 1, pageSize: NEWS_PAGE_SIZE}})
  }

  showSelectTimeSectionModal(text) {
    console.log(text)
    const time = new Date();
    time.setMinutes(0, 0, 0);
    this.setState({visible: true, beginTime: time, endTime: time, newsCustomMediaId: text});
  }

  handleSendCustomMsgOK() {
    this.setState({visible: false});
    console.log(this.state.beginTime.getTime())
    console.log(this.state.endTime.getTime())
    this.props.dispatch({type: 'weixin/sendCustomMsg',
      payload: {
        beginTime: this.state.beginTime.getTime() / 1000,
        endTime: this.state.endTime.getTime() / 1000,
        mediaId: this.state.newsCustomMediaId,
    }})
  }

  handleSendCustomMsgCancel(e) {
    console.log(e)
    this.setState({visible: false});
  }

  handleStarOK(e) {
    console.log(e)
    this.setState({starModalVisible: false});
  }

  handleStarCancel(e) {
    console.log(e)
    this.setState({starModalVisible: false});
  }

  handleRadioSelect(e) {
    console.log(e)
    this.setState({newsScope: e.target.value});
    if (e.target.value === 'all') {
      this.props.dispatch({type: 'weixin/fetchNews', payload: {page: this.props.weixin.newsPage, pageSize: NEWS_PAGE_SIZE}})
    } else if (e.target.value === 'star') {
      this.props.dispatch({type: 'weixin/fetchNewsByMediaId', payload: this.state.newsStarList})
    }
  }

  handleSearch(value) {
    console.log(value)
    if (value !== '' && value != null) {
      this.props.dispatch({type: 'weixin/fetchNewsByMediaId', payload: [value]})
      this.setState({newsScope: 'search'});
    } else {
      this.setState({searchModalVisible: true});
    }
  }

  handleSearchOK(e) {
    console.log(e)
    this.setState({searchModalVisible: false});
  }

  handleSearchCancel(e) {
    console.log(e)
    this.setState({searchModalVisible: false});
  }



  render() {
    console.log(this.state)
    console.log(this.props)
    console.log(this.props.params.appName)
    const data = this.props.weixin.newsList.map(item => {return {...item, key: item.media_id}});
    const dataStar = this.props.weixin.newsListByMediaId.items.map(item => {return {...item, key: item.media_id}});

    let columns = [{
      title: '',
      key: 'id',
      width: 35,
      render(text, record, index) {
        return index + 1;
      }
    },
//   {
//   title: '封面',
//   key: 'thumb_url',
//   render(record) {
//     return (
//       <card>
//         <img src={record.content.news_item[0].thumb_url} style={{ width: 180, height: 180 }}/>
//       </card>
//     )
//   }
// },
      {
        title: '内容',
        dataIndex: 'content',
        key: 'content',
        width: 600,
        render(text, record, index) {
          // console.log(text)
          // console.log(record)
          // console.log(index)
          return (
            <ol>
              {record.content.news_item.map(item =>{
                return <li key={item.url}><a href={item.url} target="_Blank">{item.title}</a></li>
              })}
            </ol>
          )
        },

      }, {
        title: '时间',
        dataIndex: 'time',
        key: 'time',
        width: 230,
        render(text, record) {
          const update_time = new Date(record.content.update_time * 1000);
          const create_time = new Date(record.content.create_time * 1000);
          return (
            <div>
              <p className={styles.smallSize}>{'更新于 ' + update_time.format('yyyy年MM月dd hh:mm:ss')}</p>
              <p className={styles.smallSize}>{'创建于 ' + create_time.format('yyyy年MM月dd hh:mm:ss')}</p>
            </div>
          );
        }
      }, {
        title: '操作',
        key: 'operation',
        dataIndex: 'media_id',
        width: 130,
        render: (text, record, index) => {
          // this.setState({newsCustomMediaId: text})
          return <a href="#" onClick={this.showSelectTimeSectionModal.bind(this, text)}>发送客服消息</a>;
          {/*return <button>发送客服消息</button>*/}
        }
      }, {
        title: '收藏',
        dataIndex: 'media_id',
        key: 'star',
        render: (text) => {
          return (
            <div>
              <p>
                <a href="#" onClick={(e) => {
                e.preventDefault();
                const oldList = window.localStorage.getItem(this.state.appName + '_news_media_id_star_list');
                let newList = [];
                if (oldList) {
                  {/*console.log(typeof oldList)*/}
                  {/*console.log('aa,bb'.split(','))*/}
                  {/*console.log('aa'.split(','))*/}
                  {/*console.log('aa'.split(',').push('cc'))*/}
                  {/*console.log(typeof ('aa'.split(',')))*/}
                  {/*const a = ['a','b']*/}
                  {/*a.removeByValue('a')*/}
                  {/*console.log(a)*/}


                  newList = oldList.split(',');
                  {/*console.log(typeof newList)*/}
                  {/*console.log(newList)*/}
                  if (newList.contains(text)) {
                    newList.removeByValue(text)
                  } else {
                    newList.push(text);
                  }
                  {/*this.setState({newsStarList: newList})*/}
                  {/*window.localStorage.setItem('news_media_id_star_list', newList);*/}
                } else {
                  newList.push(text);
                  {/*console.log(newList);*/}
                  {/*window.localStorage.setItem('news_media_id_star_list', newList);*/}
                  {/*window.localStorage.getItem('news_media_id_star_list');*/}
                }
                window.localStorage.setItem(this.state.appName + '_news_media_id_star_list', newList);
                console.log(window.localStorage.getItem(this.state.appName + '_news_media_id_star_list'));
                this.setState({newsStarList: newList})
                {/*const oldList2 = window.localStorage.getItem('news_media_id_star_list2');*/}
                {/*console.log(!oldList2)*/}
                {/*console.log(oldList)*/}
                {/*console.log(typeof oldList)*/}
                {/*const newList = [oldList, text]*/}
                {/*window.localStorage.setItem('news_media_id_star_list', newList);*/}
                {/*console.log(window.localStorage.getItem('news_media_id_star_list'))*/}
              }
              }>{this.state.newsStarList.contains(text) ? <span style={{color: 'red'}}>取消收藏</span> : <span>本地收藏</span>}</a>
              </p>
              <p>
                <a href="#" onClick={() => this.setState({starModalVisible: true, starMediaId: text})}>手动收藏</a>
                <Modal title={<span>手动复制存储到本地磁盘</span>}
                       visible={this.state.starModalVisible}
                       onOk={this.handleStarOK.bind(this)}
                       onCancel={this.handleStarCancel.bind(this)}
                >
                  <p>复制下面的<b>media_id</b>保存到本地磁盘。在"图文管理"页输入<b>media_id</b>搜索即可查看此条图文</p>
                  <p>{this.state.starMediaId}</p>
                </Modal>
              </p>
            </div>
          )
          ;
        }
      }];

    let columnsStar = [{
      title: '',
      key: 'id',
      width: 35,
      render(text, record, index) {
        return index + 1;
      }
    }, {
        title: '内容',
        key: 'content',
        width: 830,
        render(text, record, index) {
          return (
            <ol>
              {(record.content == null ? [] : record.content).map(item =>{
                return <li key={item.url}><a href={item.url} target="_Blank">{item.title}</a></li>
              })}
            </ol>
          )
        },
      }, {
        title: '操作',
        dataIndex: 'media_id',
        key: 'operation',
        width: 130,
        render: (text, record, index) => {
          // this.setState({newsCustomMediaId: text})
          return <a href="#" onClick={this.showSelectTimeSectionModal.bind(this, text)}>发送客服消息</a>;
          {/*return <button>发送客服消息</button>*/}
        }
      }, {
        title: '收藏',
        dataIndex: 'media_id',
        key: 'star',
        render: (text) => {
          console.log(text)
          return (
            <div>
              <p>
                <a href="#" onClick={(e) => {
                  e.preventDefault();
                  const oldList = window.localStorage.getItem(this.state.appName + '_news_media_id_star_list');
                  let newList = [];
                  if (oldList) {
                    newList = oldList.split(',');
                    if (newList.contains(text)) {
                      newList.removeByValue(text)
                    } else {
                      newList.push(text);
                    }
                  } else {
                    newList.push(text);
                  }
                  window.localStorage.setItem(this.state.appName + '_news_media_id_star_list', newList);
                  console.log(window.localStorage.getItem(this.state.appName + '_news_media_id_star_list'));
                  this.setState({newsStarList: newList})
                }
                }>{this.state.newsStarList.contains(text) ? <span style={{color: 'red'}}>取消收藏</span> : <span>本地收藏</span>}</a>
              </p>
              <p>
                <a href="#" onClick={() => this.setState({starModalVisible: true, starMediaId: text})}>手动收藏</a>
                <Modal title={<span>手动复制存储到本地磁盘</span>}
                       visible={this.state.starModalVisible}
                       onOk={this.handleStarOK.bind(this)}
                       onCancel={this.handleStarCancel.bind(this)}
                >
                  <p>复制下面的<b>media_id</b>保存到本地磁盘。在"图文管理"页输入<b>media_id</b>搜索即可查看此条图文</p>
                  <p>{this.state.starMediaId}</p>
                </Modal>
              </p>
            </div>
          );
        }
      }];

    return (
      <div className={styles.normal}>
        <div className={styles.newsArea}>
          <div className={styles.newsFilter}>
            <span style={{width: 100}}></span>
            <Radio.Group defaultValue={this.state.newsScope} value={this.state.newsScope} onChange={this.handleRadioSelect.bind(this)}>
              <Radio.Button value="all">全部图文</Radio.Button>
              <Radio.Button value="star">我的收藏</Radio.Button>
            </Radio.Group>
            <Input.Search placeholder="请输入media_id" style={{width: 200}}
                          onSearch={this.handleSearch.bind(this)}>
            </Input.Search>
          </div>
          <Table
            className={this.state.newsScope === 'all' ? styles.newsTable : styles.hidden}
            columns={columns}
            dataSource={data}
            loading={this.props.weixin.loading}
            pagination={{ total: this.props.weixin.newsTotal, current: this.props.weixin.newsPage + 1, pageSize: NEWS_PAGE_SIZE }}
            onChange={this.handleTableChange.bind(this)}
            scroll={{ y: 700 }}
            bordered
          />
          <Table
            className={(this.state.newsScope === 'star' || this.state.newsScope === 'search') ? null : styles.hidden}
            columns={columnsStar}
            dataSource={dataStar}
            loading={this.props.weixin.loading}
            onChange={this.handleTableChange.bind(this)}
            scroll={{ y: 700 }}
            bordered
          />
        </div>

        <Modal title={<span>请选择时间区间<span className={styles.smallSize}>（系统将会对此区间内关注的用户发送客服消息）</span></span>}
               visible={this.state.visible} onOk={this.handleSendCustomMsgOK.bind(this)} onCancel={this.handleSendCustomMsgCancel.bind(this)}>
          <Row gutter={20}>
            <Col span={12} className='gutter-row'>
              开始时间
              <Row>
                <Col span={3}>年</Col>
                <Col span={21}><Slider value={this.state.beginTime.getFullYear()} min={2016} max={2018}
                                       onChange={(value) => {
                                         console.log('beginTime change to', value)
                                         this.setState({beginTime: new Date(this.state.beginTime.setFullYear(value))})}}/></Col>
              </Row>
              <Row>
                <Col span={3}>月</Col>
                <Col span={21}><Slider value={this.state.beginTime.getMonth() + 1} min={1} max={12}
                                       onChange={value => this.setState({beginTime: new Date(this.state.beginTime.setMonth(value - 1))})}/></Col>
              </Row>
              <Row>
                <Col span={3}>日</Col>
                <Col span={21}><Slider value={this.state.beginTime.getDate()} min={1} max={31}
                                       onChange={value => this.setState({beginTime: new Date(this.state.beginTime.setDate(value))})}/></Col>
              </Row>
              <Row>
                <Col span={3}>时</Col>
                <Col span={21}><Slider value={this.state.beginTime.getHours()} min={0} max={23}
                                       onChange={value => this.setState({beginTime: new Date(this.state.beginTime.setHours(value))})}/></Col>
              </Row>
            </Col>
            <Col span={12} className='gutter-row'>
              结束时间
              <Row>
                <Col span={3}>年</Col>
                <Col span={21}><Slider value={this.state.endTime.getFullYear()} min={2016} max={2018}
                                       onChange={value => {
                                         console.log('endTime change to', value)
                                         this.setState({endTime: new Date(this.state.endTime.setFullYear(value))})
                                       }}/></Col>
              </Row>
              <Row>
                <Col span={3}>月</Col>
                <Col span={21}><Slider value={this.state.endTime.getMonth() + 1} min={1} max={12}
                                       onChange={value => this.setState({endTime: new Date(this.state.endTime.setMonth(value - 1))})}/></Col>
              </Row>
              <Row>
                <Col span={3}>日</Col>
                <Col span={21}><Slider value={this.state.endTime.getDate()} min={1} max={31}
                                       onChange={value => this.setState({endTime: new Date(this.state.endTime.setDate(value))})}/></Col>
              </Row>
              <Row>
                <Col span={3}>时</Col>
                <Col span={21}><Slider value={this.state.endTime.getHours()} min={0} max={23}
                                       onChange={value => this.setState({endTime: new Date(this.state.endTime.setHours(value))})}/></Col>
              </Row>
            </Col>
          </Row>
          <Row>
            <Col span={24}>{
              <span>
                {this.state.beginTime.format('yyyy年MM月dd hh:mm:ss')}
                <b>&nbsp;&nbsp;至&nbsp;&nbsp;</b>
                {this.state.endTime.format('yyyy年MM月dd hh:mm:ss')}
                </span>
            }</Col>
            <Col span={24}><Button onClick={() => {
              const time = new Date();
              time.setMinutes(0, 0, 0);
              this.setState({beginTime: time, endTime: time});
            }}>重置时间</Button></Col>
          </Row>
        </Modal>
        <Modal visible={this.state.searchModalVisible}
               onOk={this.handleSearchOK.bind(this)} onCancel={this.handleSearchCancel.bind(this)}>
          <p><b>media_id</b>不能为空</p>
        </Modal>
      </div>
    );
  }
}

News.contextTypes = {
  router: React.PropTypes.object
}

Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

Array.prototype.contains = function (obj) {
  let i = this.length;
  while (i--) {
    if (this[i] === obj) {
      return true;
    }
  }
  return false;
}

Array.prototype.removeByValue = function(obj) {
  for(var i=0; i<this.length; i++) {
    if(this[i] === obj) {
      this.splice(i, 1);
      break;
    }
  }
}


export default News;
